package com.pipayshop.utils;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;

import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.web3j.crypto.Keys;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;

public class HDWalletGenerator {

    /**
     * 生成 HD Wallet
     */
    public static String generateHDWallet(Long id) {
        try {
            // 1. 生成助记词（12 个单词）
//            MnemonicCode mnemonicCode = new MnemonicCode();
//            SecureRandom secureRandom = new SecureRandom();
//            byte[] entropy = new byte[16]; // 128 位随机数
//            secureRandom.nextBytes(entropy); // 填充数组为安全随机数
//            String mnemonic = String.join(" ", mnemonicCode.toMnemonic(entropy));
            String mnemonic = "ginger rely soup memory february recipe uncover basket provide report priority plug";
//            System.out.println("Mnemonic: " + mnemonic);

            // 2. 使用助记词生成种子
            String passphrase = ""; // 可选密码
            DeterministicSeed seed = new DeterministicSeed(mnemonic, null, passphrase, System.currentTimeMillis());

            // 3. 创建 DeterministicKeyChain
            DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();

            // 4. 构造 BIP44 路径：m/44'/60'/0'/0/0

                List<ChildNumber> bip44Path = Arrays.asList(
                        new ChildNumber(44, true), // BIP44
                        new ChildNumber(60, true), // 以太坊的货币代码
                        new ChildNumber(0, true),  // 账户索引
                        ChildNumber.ZERO,          // 外部链
                        new ChildNumber(Math.toIntExact(id), false)  // 地址索引
                );

                // 5. 派生密钥
                DeterministicKey key = keyChain.getKeyByPath(bip44Path, true);

                // 6. 提取以太坊地址
                byte[] publicKeyBytes = key.getPubKeyPoint().getEncoded(false); // 获取未压缩公钥
                String ethereumAddress = "0x" + Keys.getAddress(Numeric.toHexStringNoPrefix(publicKeyBytes).substring(2));
//                System.out.println("Address " + id + ": " + ethereumAddress);
                // 打印私钥（用于备份或导入）
//                String privateKeyHex = Numeric.toHexStringNoPrefix(key.getPrivKeyBytes());
//                System.out.println("Private Key " + i + ": " + privateKeyHex);
                System.out.println("=========================");
                System.out.println("ethereumAddress："+ethereumAddress);
                return ethereumAddress;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        generateHDWallet(0L);
    }
}



